package com.itany.shop.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author MissChen
 * @date 2024年05月17日 13:55
 */
@WebFilter("/*")
public class LogAnnotationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("--------注解版：初始化过滤器----------");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("------------注解版：过滤器的核心业务逻辑-----------");
        // System.out.println(servletRequest instanceof HttpServletRequest);
        // System.out.println(servletResponse instanceof HttpServletResponse);

        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String ip=request.getRemoteAddr();
        String uri=request.getRequestURI();
        System.out.println(ip+"在"+new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date())+"访问了"+uri+"请求");

        //FilerChain用于判断当前过滤器是否对外请求放行
        // 如果请求不放行，则停在当前过滤器中无法出去
        // 放行，放行后请求进入下一个过滤器或者对应的Servlet中去
        // 如果需要放行，则执行以下方法，如果不需要放行，则不执行以下方法即可
        chain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("--------注解版：销毁过滤器-------");
    }
}
